<template>
    <BasicModal
        v-bind="$attrs"
        title="编辑租客"
        width="700px"
        okText="更新"
        @register="register"
        @cancel="cancelFn"
        @ok="okFn"
    >
        <a-form :labelCol="{ span: 6 }" :wrapperCol="{ span: 16 }">
            <a-form-item v-bind="validateInfos.name" label="租客姓名">
                <a-input placeholder="请输入租客姓名" v-model:value="form.name" />
            </a-form-item>
            <a-form-item label="密码">
                <a-input type="password" placeholder="请输入密码" v-model:value="form.password" />
            </a-form-item>
            <a-form-item v-bind="validateInfos.mobile" label="电话">
                <a-input placeholder="请输入电话" v-model:value="form.mobile" />
            </a-form-item>
            <a-form-item label="邮箱">
                <a-input placeholder="请输入邮箱" v-model:value="form.email" />
            </a-form-item>
            <a-form-item v-bind="validateInfos.id_card" label="身份证号">
                <a-input placeholder="请输入身份证号" v-model:value="form.id_card" />
            </a-form-item>
            <a-form-item label="身份证正面照">
                <a-upload
                    list-type="picture-card"
                    :fileList="form.id_card_front_list"
                    :beforeUpload="beforeFrontUpload"
                    @preview="handlePreview"
                    @change="handleFrontChange"
                >
                    <div v-if="form.id_card_front_list.length == 0">
                        <UploadOutlined />
                        <div class="ant-upload-text">上传正面照</div>
                    </div>
                </a-upload>
            </a-form-item>
            <a-form-item label="身份证背面照">
                <a-upload
                    list-type="picture-card"
                    :fileList="form.id_card_back_list"
                    :beforeUpload="beforeBackUpload"
                    @preview="handlePreview"
                    @change="handleBackChange"
                >
                    <div v-if="form.id_card_back_list.length == 0">
                        <UploadOutlined />
                        <div class="ant-upload-text">上传背面照</div>
                    </div>
                </a-upload>
            </a-form-item>
        </a-form>
        <Modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
            <img alt="example" style="width: 100%" :src="previewImage" />
        </Modal>
    </BasicModal>
</template>

<script lang="ts">
    import { defineComponent, reactive, ref, onUpdated, toRaw, PropType } from 'vue'
    import { BasicModal, useModalInner } from '/@/components/Modal'
    import { DataItem } from '/@/api/user/user/model'
    import { message, Modal } from 'ant-design-vue'
    import { UploadOutlined } from '@ant-design/icons-vue'
    import { useForm } from '@ant-design-vue/use'
    import { getBase64 } from '/@/utils/dateUtil'
    import { updateApi } from '/@/api/user/user/index'
    import { getToken } from '/@/utils/auth'
    import { UploadFileParams } from '/@/utils/http/axios/types'

    export default defineComponent({
        props: {
            selectItem: Object as PropType<DataItem>,
        },
        components: { BasicModal, UploadOutlined, Modal },
        setup(props, context) {
            // 表单
            const form = reactive<any>({
                name: '',
                mobile: '',
                email: '',
                password: '',
                id_card: '',
                id_card_front: '',
                id_card_front_list: [],
                id_card_back: '',
                id_card_back_list: [],
            })

            // 初始化表格信息
            onUpdated(() => {
                if (getVisible) {
                    // console.log(props.selectItem);
                    form.name = props.selectItem?.name
                    form.mobile = props.selectItem?.mobile
                    form.email = props.selectItem?.email
                    form.id_card = props.selectItem?.id_card

                    if (props.selectItem?.id_card_front) {
                        form.id_card_front = props.selectItem?.id_card_front
                        form.id_card_front_list = [
                            {
                                uid: '-1',
                                url: props.selectItem.id_card_front,
                            },
                        ]
                    } else {
                        form.id_card_front = ''
                        form.id_card_front_list = []
                    }

                    if (props.selectItem?.id_card_back) {
                        form.id_card_back = props.selectItem?.id_card_back
                        form.id_card_back_list = [
                            {
                                uid: '-2',
                                url: props.selectItem.id_card_back,
                            },
                        ]
                    } else {
                        form.id_card_back = ''
                        form.id_card_back_list = []
                    }
                }
            })

            // 表单校验
            const rulesRef = reactive({
                name: [
                    {
                        required: true,
                        message: '请输入租客姓名',
                    },
                ],
                mobile: [
                    {
                        required: true,
                        message: '请输入电话',
                    },
                ],
                id_card: [
                    {
                        required: true,
                        message: '请输入身份证',
                    },
                ],
            })
            const { resetFields, validate, validateInfos } = useForm(form, rulesRef)

            // 图片切换
            const beforeFrontUpload = (file: File) => {
                //   console.log(file);
                form.id_card_front_list = [file]
                return false
            }
            const beforeBackUpload = (file: File) => {
                //   console.log(file);
                form.id_card_back_list = [file]
                return false
            }
            // 图片预览
            const previewVisible = ref(false)
            const previewImage = ref('')
            const handleCancel = () => {
                previewVisible.value = false
            }
            const handlePreview = async (file: File) => {
                if (!file.url && !file.preview) {
                    file.preview = await getBase64(file.originFileObj)
                }
                previewImage.value = file.url || file.preview
                previewVisible.value = true
            }
            const handleFrontChange = ({ fileList }) => {
                form.id_card_front_list = fileList
            }
            const handleBackChange = ({ fileList }) => {
                form.id_card_back_list = fileList
            }

            // 弹窗管理
            const [register, { closeModal, getVisible, changeLoading }] = useModalInner()
            const cancelFn = () => {
                closeModal()
            }
            const okFn = () => {
                // 更新操作
                validate()
                    .then(async () => {
                        const info = toRaw(form)
                        console.log(info)

                        // 判断是否上传身份证照片
                        if (
                            info.id_card_front_list.length != 1 ||
                            info.id_card_back_list.length != 1
                        ) {
                            message.error('请上传身份证图片!')
                            return
                        }

                        const formData: UploadFileParams = {
                            name: [],
                            file: [],
                            filename: [],
                        }

                        if (info.id_card_front_list[0].originFileObj) {
                            formData.name?.push('id_card_front')
                            formData.file?.push(info.id_card_front_list[0].originFileObj)
                            formData.filename?.push('id_card_front')
                        }

                        if (info.id_card_back_list[0].originFileObj) {
                            formData.name.push('id_card_back')
                            formData.file.push(info.id_card_back_list[0].originFileObj)
                            formData.filename.push('id_card_back')
                        }

                        try {
                            changeLoading(true)
                            formData.data = {
                                token: getToken(),
                                id: props.selectItem?.id,
                                password: info.password,
                                name: info.name,
                                mobile: info.mobile,
                                email: info.email,
                                id_card: info.id_card,
                            }
                            console.log(formData)
                            const res = await updateApi(formData)
                            console.log(res)
                            changeLoading(false)
                            // 更新成功
                            message.success('更新成功!')
                            context.emit('updateData')
                            closeModal()
                        } catch (err) {
                            changeLoading(false)
                            console.log(err)
                        }
                    })
                    .catch((err) => {
                        console.log(err)
                    })
            }

            return {
                register,
                cancelFn,
                okFn,
                form,
                validateInfos,
                beforeFrontUpload,
                beforeBackUpload,
                previewVisible,
                handlePreview,
                handleFrontChange,
                handleBackChange,
                handleCancel,
                previewImage,
            }
        },
    })
</script>

<style></style>
